package com.bdqn.service.impl;

import com.bdqn.mapper.MenuMapper;
import com.bdqn.mapper.RoleMapper;
import com.bdqn.pojo.Menu;
import com.bdqn.pojo.Role;
import com.bdqn.service.RoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    RoleMapper roleMapper;

    @Autowired
    MenuMapper menuMapper;

    @Override
    public List<Role> getAll() {
        return roleMapper.selectAll();
    }

    @Override
    public PageInfo<Role> selectPage(int pageNum, int pageSize, String name) {
        //开始分页,设置当前页的页号和每页显示的条数
        PageHelper.startPage(pageNum,pageSize);
        //获取所有的角色信息
        List<Role> list=roleMapper.selectByName(name);
        //获取当前页的信息对象
        PageInfo<Role> pageInfo=new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public int addRole(Role role) {
        return roleMapper.add(role);
    }

    @Override
    public int addRoleMenu(int rid, List<Integer> pids, List<Integer> cids) {
        //删除角色拥有的所有菜单
        roleMapper.deleteById(rid);
        return roleMapper.addRoleMenu(rid,pids,cids);
    }

    @Override
    public List<Menu> selectRoleMenus(int rid) {
        //根据角色编号，查询角色的父菜单
        List<Menu> list=menuMapper.selectByRid(rid);
        //根据父菜单，查询角色的子菜单
        //根据父菜单编号，查询父菜单下所有的子菜单
        for (Menu pmenu:list) {
            //获取父菜单编号
            int pid=pmenu.getMenuId();
            //查询父菜单下所有的子菜单
            List<Menu> childeMenuList=menuMapper.selectChildMenusByRidAndPid(rid,pid);
            //放到父菜单下
            pmenu.setChildMenuList(childeMenuList);
        }
        return list;
    }

    @Override
    public List<Integer> getRids(int uid) {
        return roleMapper.selectRids(uid);
    }

    @Override
    public List<Integer> getRoleMids(int rid) {
        return roleMapper.selectMids(rid);
    }

    @Override
    public int addRoleMids(int rid, List<Integer> mids) {
        //删除角色拥有权限菜单
        roleMapper.deleteMids(rid);
        //添加新授予的权限菜单
        int row=roleMapper.addRoleMenu(rid,mids,new ArrayList<Integer>());
        return row;
    }
}
